package cn.gov.pbc.tims.controller;

import java.io.File;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.annotation.Resource;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import javax.mail.search.SubjectTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.pop3.POP3Folder;

import cn.gov.pbc.tims.entity.Dept;
import cn.gov.pbc.tims.entity.Fileup;
import cn.gov.pbc.tims.entity.Mail;
import cn.gov.pbc.tims.entity.Task;
import cn.gov.pbc.tims.entity.User;
import cn.gov.pbc.tims.service.CommonService;
import cn.gov.pbc.tims.service.Pop3MailService;
import cn.gov.pbc.tims.serviceInt.IMailService;
import cn.gov.pbc.tims.util.FileOperateUtil;
import cn.gov.pbc.tims.util.Operator;
import cn.gov.pbc.tims.util.PageData;
import cn.gov.pbc.tims.util.Result;

@Controller
@RequestMapping("/mail")
public class MailController{
	@Autowired
	private Operator operator;
	@Autowired
	private CommonService commonService;
	private IMailService mailService;
	@Resource(name="imapMailService")
	public void setMailService(IMailService mailService) {
		this.mailService = mailService;
	}
	public  Folder getFolder () throws Exception {
        String userName=operator.getUser().getEmailAddress();
        String password = operator.getUser().getEmailPassword(); // 邮箱的密码      
		return   mailService.getFolder(userName, password);
	}
	@RequestMapping("/getMail") 
	public  @ResponseBody PageData getMail (Integer page, Integer rows,HttpServletRequest request) throws Exception {
		Folder folder = getFolder();
		PageData grid_data= mailService.getMail(folder, page, rows, request);
		return grid_data;
	}
	
   @RequestMapping("/getAttachment") 
	public void getAttachment(String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception
	{ 
	   Folder folder=getFolder();
	   mailService.getAttachment(folder, uid, fileName, request, response);
	}
   
   @RequestMapping("/getDocContent") 
	public @ResponseBody Result getDocContent(String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception
	{
	    Result  result=new Result();
	    Folder folder=this.getFolder();
	    String content=mailService.getDocContent(folder, uid, fileName, request, response);
	    result.setData(content);
	    String contentType = "application/octet-stream";  
		return result;
	}
   public  List<Fileup> saveAttachMents(Folder folder,String uid,String path) throws Exception
	{
	   List<Fileup> fileUps=null;
	   Message message1=mailService.getMessageByUid(folder,uid);
	  if(null!=message1)
		fileUps=saveAttachMents(message1,path);
		folder.close();
		folder.getStore().close();
		return fileUps;
	}
   public List<Fileup> saveAttachMents (Part part,String path) throws Exception {
		List fileups=new ArrayList<Fileup>();
		String fileName = "";

		if (part.isMimeType("multipart/*")) {

			Multipart mp = (Multipart) part.getContent();

			for (int i = 0; i < mp.getCount(); i++) {

				BodyPart mPart = mp.getBodyPart(i);

				String disposition = mPart.getDisposition();

				if ((disposition != null)

						&& ((disposition.toLowerCase().equals(Part.ATTACHMENT)))) {

					fileName = mPart.getFileName();
					fileName = MimeUtility.decodeText(fileName);
					//System.out.println("decode filename is" + fileName);
					System.out.println("size21="+mPart.getSize());
					System.out.println("size21="+mPart.getInputStream().available());
					Fileup  fileup=saveFile(path,fileName, mPart.getInputStream());
					fileups.add(fileup);

				} else if (mPart.isMimeType("multipart/*")) {

					saveAttachMents(mPart,path);

				} else {

					fileName = mPart.getFileName();
					if ((fileName != null) && ((fileName.toLowerCase().indexOf("gb2312") != -1)||(fileName.toLowerCase().indexOf("gbk") != -1))) {
						fileName = MimeUtility.decodeText(fileName);
						System.out.println("size22="+mPart.getInputStream().available());
						Fileup  fileup=saveFile(path,fileName, mPart.getInputStream());
						fileups.add(fileup);
					}
				}

			}
		} else if (part.isMimeType("message/rfc822")) {

			saveAttachMents((Part) part.getContent(),path);
		}
		return fileups;
	}
   public Fileup saveFile(String path,String fileName,InputStream in){
	   Fileup  fileup=new Fileup();
	   try {
		    
			//重命名文件名为 java.util.uuid 生成的随机串  + 后缀
			//String saveFileName = UUID.randomUUID().toString() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
			DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");		
			//DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String str = format.format(Calendar.getInstance().getTime());
			String saveFileName=fileName.substring(0,fileName.lastIndexOf("."))+"By"+operator.getUser().getName()+str+"." + fileName.substring(fileName.lastIndexOf(".") + 1);
			FileOperateUtil.saveFile(saveFileName, path, in);
			//String dispName=fileName.substring(0,fileName.lastIndexOf("."))+"By"+operator.getUser().getName()+str+"." + fileName.substring(fileName.lastIndexOf(".") + 1);
			String dispName=fileName;
			fileup.setOrigName(fileName);
			fileup.setFinalName(saveFileName);
			fileup.setDispName(dispName);
			fileup.setPath("upload"+File.separator);
			fileup.setCreatedDate(Calendar.getInstance().getTime());
			User op = operator.getUser();
			fileup.setCreator(op.getName());
			fileup.setCreatorCode(op.getCode());
			fileup.setDeptId(op.getDeptId());
			fileup.setJgId(op.getJgId());
			commonService.save(fileup);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileup;
   }
   @RequestMapping(value = "/mailTask")
	public @ResponseBody Result mailTask(Task entity,String messageId,HttpServletRequest request) throws Exception {
       Folder folder= this.getFolder();
	   String dirName="upload";
	   String path = request.getSession().getServletContext().getRealPath("/" + dirName + "/");//指代根目录下的excelUpload目录
	   List<Fileup> fileups=saveAttachMents(folder,messageId, path);
	   StringBuffer sb=new StringBuffer("");
	   if(fileups.size()>0)
	   {
		   for(Fileup fileup:fileups)
		   {  
			   String name=fileup.getOrigName();
			   if(null!=fileup.getOrigName())
				   name=fileup.getDispName();
		      if(sb.length()==0)
			    sb.append("<a href='"+dirName+File.separator+fileup.getFinalName()+"'  target='_blank' >"+name+"</a>");
		      else
		        sb.append(",<a href='"+dirName+File.separator+fileup.getFinalName()+"'  target='_blank' >"+name+"</a>");
			      
		   }
	   }
      if(sb.length()!=0)   
    	  entity.setAttachments(sb.toString());
		User user=operator.getUser();
		Integer id=user.getDeptId();
		 if(null!=id)
			 {
				 Dept dept=commonService.get(Dept.class, id);
				 if(!dept.getLevel().equals("1"))
					 dept=commonService.get(Dept.class, dept.getUpDeptId());
				 entity.setL1DeptId(dept.getId());
			 }
		entity.setCreator(user.getName());
		entity.setCreatorCode(user.getCode());
		entity.setJgId(user.getJgId());
		entity.setJgName(user.getJgName());
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format.format(Calendar.getInstance().getTime());
		entity.setContent(entity.getContent()+"\r\n"+ "          submited by "+user.getName()+" at "+str);
		entity.setStatus("0");
		commonService.saveOrUpdate(entity);
	 
	 	Result result = new Result();
		result.setMsg("保存成功！");
		result.setCode(0);

		return result;
	} 
 }
